<template>
  <div class="h-[100%]">
    <vxe-grid ref="tableRef" v-bind="tableOptions">
      <template #time_limit="{row}">
        <div>
          {{row?.time_limit?.join('-')||"-"}}天
        </div>
      </template>
    </vxe-grid>
    <Log
      dialog
      v-model="logVisible"
      :autoLoad="false"
      tag="channel.transport-cost"
      :business_id="logId"
      @close="logId = ''"
    />
  </div>
</template>

<script setup lang="jsx">
import { useRoute } from 'vue-router'
import Log from '@/components/Log/index.vue'
import { transportCostList } from '../../api/index'

const props = defineProps({
  id: { type: String, default: '' },
  channelId: { type: Number, default: '' },
  params: { type: Object, default: () => ({}) },
})

const route = useRoute()

const emit = defineEmits([
  'status',
  'edit',
  'update:deliverMode',
  'update:billingType',
])

const tableRef = ref()
const logVisible = ref(false)
const logId = ref('')
const renderColumns = (other = []) => {
  return [
    { fixed: 'left', width: 50, type: 'checkbox' },
    { fixed: 'left', width: 80, title: '编号', field: 'id' },
    { fixed: 'left', title: '运价文件名', minWidth: 200, field: 'file_name' },
    { title: '状态', width: 100, field: 'status_text' },
    { title: '物流商', width: 240, field: 'logistics_name' },
    { title: '中文渠道名称', width: 200, field: 'channel_name' },
    { title: '计费类型', width: 200, field: 'billing_type_text' },
    { title: '运输类型', width: 200, field: 'transport_type_text' },
    { title: '始发站', width: 200, field: 'shipping_address' },
    { title: '目的地', width: 200, field: 'arrival_address' },
    { title: '目的地二字码', width: 200, field: 'destination_country' },
    { title: '区域', width: 200, field: 'regions' },
    { title: '货物类型', width: 200, field: 'goods_attrs_text' },
    { title: '时效', width: 200, field: 'time_limit',slots:{default:"time_limit"} },
    { title: '抛重计算因子', width: 200, field: 'count_reason' },
    { title: '备注', width: 200, field: 'remark' },
    ...other,
    {
      title: '操作',
      minWidth: 200,
      fixed: 'right',
      align: 'center',
      slots: {
        default: ({ row }) => {
          return (
            <div>
              <el-button link type='primary' onClick={() => handleEdit(row.id)}>
                编辑
              </el-button>
              <el-button
                link
                type={row.status === 0 ? 'primary' : 'danger'}
                onClick={() => handleStatus(row)}
              >
                {{ 0: '启用', 1: '禁用' }[row.status]}
              </el-button>
              <el-button link type='primary' onClick={() => handleLog(row)}>
                日志
              </el-button>
            </div>
          )
        },
      },
    },
  ]
}

const tableOptions = reactive({
  pagerConfig: { pageSize: 20 },
  round: true,
  height: 'auto',
  autoHidden: true,
  columnConfig: {
    resizable: true,
  },
  columns: renderColumns(),
  proxyConfig: {
    autoLoad: true, // 是否自动加载查询数据
    props: {
      result: 'data',
      total: 'total',
    },
    ajax: {
      query: ({ page }) => {
        return handleReq(page)
      },
    },
  },
})
const flage = ref(false)
const handleReq = async page => {
  const { id } = route.query
  try {
    const { params,channelId } = props
    const res = await transportCostList({
      ...params,
      ...page,
      channel_id: flage.value?channelId:id,
    })
    flage.value = true
    const { header, body, delivery_mode, billing_type } = res.data || {}
    const {total} = res||{}
    const _surcharge = header?.surcharge || []
    const _detailHead = [...convertHeader(header?.detail)]
    const _surchargeHead = [...convertSurcharge(_surcharge)]

    const _columns = [..._detailHead, ..._surchargeHead]

    const _body = body.map(n => {
      let _obj = {}
      n.detail.forEach((v, index) => {
        for (let field in v) {
          _obj[`${field}${index}`] = v[field]
        }
      })
      _surcharge.map(n => {
        _obj[`surcharge${n.cost_ident}`] = n.cost_value
      })
      return { ...n, ..._obj }
    })
    tableRef.value.loadColumn(renderColumns(_columns))
    emit('update:deliverMode', delivery_mode)
    emit('update:billingType', billing_type)
    return { data: _body, total }
  } catch (e) {
    console.error(e)
  }
}

const convertHeader = (arr = []) => {
  let _arr = []
  for (let i in arr) {
    const _item = arr[i]
    for (let n in _item) {
      _arr.push({
        title: _item[n],
        width: 200,
        field: `${n}${i}`,
      })
    }
  }
  return _arr
}

const convertSurcharge = (arr = []) => {
  return arr.map(n => ({
    title: n.cost_label,
    width: 200,
    field: `surcharge${n.cost_ident}`,
  }))
}

const handleLog = item => {
  logId.value = item.id
  logVisible.value = true
}

const handleEdit = id => {
  emit('edit', id)
}

const handleStatus = item => {
  emit('status', item.id, item.status ? 0 : 1)
}

defineExpose({ tableRef })
</script>
<style lang="scss" scoped>
:deep(.vxe-pager){
  height: 40px;
}
</style>
